const logger = require('./logger')


/*
* 存儲通道信息，包含消費者和生產者
* */
class TransportInfo{
    constructor(transport) {
        this.id = transport.id
        this.transport = transport
        this._consumerMap = new Map()
        this._producerMap = new Map()
        this._isConnect = false;
        this.event()
    }

    setConnect(connect) {
        this._isConnect = connect
    }

    isConnect(){
        return this._isConnect;
    }

    event(){
        this.transport.on('rtcp', (packet) => {
            logger.info('packet', packet)
        })
    }

    addConsumer(consumer){
        this._consumerMap.set(consumer.id, consumer)
        consumer.observer.on('close', ()=> {
            logger.info('close')
        })
    }

    removeConsumer(id) {
       const consumer = this._consumerMap.get(id)
        if (consumer !== undefined) {
            this._consumerMap.delete(id)
            consumer.close()
        }
    }

    getConsumer(){
        return this._consumerMap
    }

    getConsumeById(id){
        return this._consumerMap.get(id)
    }

    async getTransportStats(){
        return await this.transport.getStats()
    }

    async addProducer(producer){
        producer.enableTraceEvent(['rtp'])
        // const stats =  await producer.getStats();
        // logger.info(stats)
        var peer = 0
        producer.on('trace', (trace)=> {
            // if ((trace.info.sequenceNumber-peer) > 1) {
            //     logger.info(producer.id, trace)
            //     logger.info(producer.id, trace.info.sequenceNumber - peer, trace.info.sequenceNumber)
            // }
            //if (trace.info.wideSequenceNumber !== undefined) {
            //    console.log('wideSequenceNumber', trace.info)
            //}
           peer = trace.info.sequenceNumber
        })
        this._producerMap.set(producer.id, producer)
    }

    removeProducer(id) {
        const producer = this._producerMap.get(id)
        if (producer !== undefined) {
            producer.close()
            this._producerMap.delete(id)
        }

    }

    getProducer(){
        return this._producerMap
    }

    getProducerById(id){
        return this._producerMap.get(id)
    }

    async createProducer(kind, rtpParameters, appData) {
        const producer =  await this.transport.produce({
            kind,
            rtpParameters,
            appData
        })
        await this.addProducer(producer)
        return producer
    }


    async createConsumer(producer, rtpCapabilities) {
        const consumer = await this.transport.consume({
            producerId: producer.id,
            rtpCapabilities: rtpCapabilities,
            enableRtx       : true,
            paused          : false
        })
        this.addConsumer(consumer)
        return consumer
    }
}

/**
 * 用户信息类
 */
class Member {
    constructor(peerId, client) {
        this.peerId = peerId;
        this.client = client
        this._transportInfoMap = new Map();
    }

    setTransport(transport){
        this._transportInfoMap.set(transport.id, new TransportInfo(transport));
    }

    getTransportById(id){
        return this._transportInfoMap.get(id)
    }

    getTransport(){
        return this._transportInfoMap
    }

    async connectTransport(id, dtlsParameters) {
        //为了容错客户端重connect 原本的连接
        if (!this._transportInfoMap.get(id).isConnect()) {
            this._transportInfoMap.get(id).setConnect(true)
            return await  this._transportInfoMap.get(id).transport.connect({
                dtlsParameters
            })
        }
    }

    removeTransport(id){
        this._transportInfoMap.delete(id)
    }

    /*
    * 生产关闭了，对应的消费也关闭
    * */
    removeConsumer(producerId){
        for (const [transportId, transportInfo] of this._transportInfoMap) {
            for (const [consumeId, consume] of transportInfo.getConsumer()) {
                if (consume.producerId === producerId) {
                    logger.info("removeConsume", consumeId)
                    transportInfo.removeConsumer(consumeId)
                    consume.close()
                }
            }
        }
   }

   getProducer(produceId){
       for (const [transportId, transportInfo] of this._transportInfoMap) {
           for (const [id, producer] of transportInfo.getProducer()) {
               if (id === produceId) {
                   return producer
               }
           }
       }
   }

    destroy(){
        const memberDestroy = {
            transport: [],
            consume: [],
            produce: []
        }
        for (const [transportId, transportInfo] of this._transportInfoMap) {
            memberDestroy.transport.push(transportInfo.transport.id)
            for (const[producerId, producer] of transportInfo.getProducer()) {
                memberDestroy.produce.push(producerId)
                transportInfo.removeProducer(producerId)
            }
            for (const [consumeId, consumer] of transportInfo.getConsumer()) {
                memberDestroy.consume.push(consumeId)
                transportInfo.removeConsumer(consumeId)
            }
            transportInfo.transport.close()
        }
        return memberDestroy
    }


}

module.exports = {Member, TransportInfo}
